package org.jeecg.modules.modelBase.controller;

import java.net.URLEncoder;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.dataSet.entity.DataSet;
import org.jeecg.modules.dataSet.service.IDataSetService;
import org.jeecg.modules.modelBase.entity.ModelBase;
import org.jeecg.modules.modelBase.entity.ModelBaseData;
import org.jeecg.modules.modelBase.service.IModelBaseDataService;
import org.jeecg.modules.modelBase.service.IModelBaseService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.userFormula.entity.UserFormula;
import org.jeecg.modules.util.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 模型库
 * @Author: jeecg-boot
 * @Date:   2023-06-28
 * @Version: V1.0
 */
@Api(tags="模型库")
@RestController
@RequestMapping("/modelBase/modelBase")
@Slf4j
public class ModelBaseController extends JeecgController<ModelBase, IModelBaseService> {
	@Autowired
	private IModelBaseService modelBaseService;
	@Autowired
	private IDataSetService dataSetService;
	@Autowired
	private IModelBaseDataService modelBaseDataService;
	@Value("${zf-jqxx-service.url}")
	private String zfserviceUrl;
	
	/**
	 * 分页列表查询
	 *
	 * @param modelBase
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "模型库-分页列表查询")
	@ApiOperation(value="模型库-分页列表查询", notes="模型库-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<ModelBase>> queryPageList(ModelBase modelBase,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ModelBase> queryWrapper = QueryGenerator.initQueryWrapper(modelBase, req.getParameterMap());
		Page<ModelBase> page = new Page<ModelBase>(pageNo, pageSize);
		IPage<ModelBase> pageList = modelBaseService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param modelBase
	 * @return
	 */
	@AutoLog(value = "模型库-添加")
	@ApiOperation(value="模型库-添加", notes="模型库-添加")
	//@RequiresPermissions("modelBase:tb_model_base:add")
	@PostMapping(value = "/add")
	@Transactional(rollbackFor = Exception.class)
	public Result<ModelBase> add(@RequestBody ModelBase modelBase) {
		Date d = new Date();
		modelBase.setCode("MX_" + DateUtils.yyyymmddhhmmss.get().format(d));
		LambdaQueryWrapper<DataSet> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(DataSet::getCode, modelBase.getDataSetCode());
		Optional<DataSet> dataSetPresent = dataSetService.list(queryWrapper).stream().findFirst();
		if(dataSetPresent.isPresent()){
			modelBase.setSlotNo(dataSetPresent.get().getSlotNo());
		}
		try {
			Map<String, Object> paramsMap = new HashMap<>();
			paramsMap.put("model_name",modelBase.getCode());
			paramsMap.put("dataset_name",modelBase.getDataSetCode());
//			if ("特征值数据".equals(modelBase.getDataType())) {
//				paramsMap.put("use_resample_data", "是");
//			} else {
//				paramsMap.put("use_resample_data", "否");
//			}
			paramsMap.put("use_resample_data", "否");
			paramsMap.put("time_interval",modelBase.getTimeInterval());
			paramsMap.put("interval_unit",modelBase.getIntervalUnit());
			paramsMap.put("select_method",modelBase.getMethod());
			paramsMap.put("predict_property",modelBase.getPredictProperty());
			paramsMap.put("train_method",modelBase.getType());
			paramsMap.put("batch_size",modelBase.getBatchSize());
			paramsMap.put("epochs",modelBase.getEpochs());
			paramsMap.put("generate_pic",true);
			String url = zfserviceUrl + "/ml/train";
			JSONObject object = HttpClientUtil.sendPost(url,paramsMap);
			if (object == null) {
				return Result.error("保存失败");
			}
			if (object.get("code") != null && Integer.parseInt(object.get("code").toString()) == 0) {
				modelBaseService.save(modelBase);
				ModelBaseData modelBaseData = new ModelBaseData();
				modelBaseData.setModelBaseId(modelBase.getId());
				modelBaseData.setDataJson(object.get("data").toString());
				modelBaseDataService.save(modelBaseData);
				return Result.OK("操作成功",modelBase);
			} else {
				if (object.containsKey("message") && object.get("message") != null) {
					return Result.error(object.get("message").toString());
				} else {
					return Result.error("保存失败");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage(), e);
			return Result.error("保存失败，请联系管理员");
		}
	}
	
	/**
	 *  编辑
	 *
	 * @param modelBase
	 * @return
	 */
	@AutoLog(value = "模型库-编辑")
	@ApiOperation(value="模型库-编辑", notes="模型库-编辑")
	//@RequiresPermissions("modelBase:tb_model_base:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody ModelBase modelBase) {
		modelBaseService.updateById(modelBase);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "模型库-通过id删除")
	@ApiOperation(value="模型库-通过id删除", notes="模型库-通过id删除")
	//@RequiresPermissions("modelBase:tb_model_base:delete")
	@Transactional(rollbackFor = Exception.class)
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		modelBaseService.removeById(id);
		LambdaQueryWrapper<ModelBaseData> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(ModelBaseData::getModelBaseId, id);
		modelBaseDataService.remove(queryWrapper);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "模型库-批量删除")
	@ApiOperation(value="模型库-批量删除", notes="模型库-批量删除")
	//@RequiresPermissions("modelBase:tb_model_base:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.modelBaseService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "模型库-通过id查询")
	@ApiOperation(value="模型库-通过id查询", notes="模型库-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<ModelBase> queryById(@RequestParam(name="id",required=true) String id) {
		ModelBase modelBase = modelBaseService.getById(id);
		if(modelBase==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(modelBase);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param modelBase
    */
    //@RequiresPermissions("modelBase:tb_model_base:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ModelBase modelBase) {
        return super.exportXls(request, modelBase, ModelBase.class, "模型库");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("modelBase:tb_model_base:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ModelBase.class);
    }

}
